import { observable, action } from 'mobx';
import BaseStore from './BaseStore';
import { Tools, Bubble } from 'weaver-mobile'
import { MapPage } from 'weaver-mobile-page';
import base from '../util/base';
const getLabel = Tools.getLabel;

const getCurrentPosition = MapPage.getCurrentPosition;


export class LocationMap extends BaseStore {

    @observable locationInfo = { loaded: false, address: getLabel(126181, '暂无位置信息') };
    @observable editFieldIds = [];//字段属性为可编辑的位置字段id
    @observable fieldObj = {};

    //获取定位
    getLocaiton = (func) => {
        if(window.em && window.em.ready) {
            window.em.ready(() => {
                this.getLocationByCom(func);
            });
        } else {
            this.getLocationByCom(func);
        }
    }

    @observable mapPageStore = new MapPage.Store({ route: '/map-page' }); //MapPage地图组件store
    //调用组件方法获取位置
    getLocationByCom = (func) => {
        !this.locationInfo.loaded  && getCurrentPosition().then((result) => {
            let locationInfo = { loaded: true, position: result.position, address: result.address };

            if(result.status == -1) {//获取位置失败
                locationInfo.address = getLabel(126181, '暂无位置信息');
            }

            //企业微信定位只返回经纬度，不返回地址字符串，这里需要临时做下补偿，请求接口获取下地址，后续组件库会把这个做掉，这段代码可以去掉。
            if(result.position && result.position.length == 2 && (result.address == null || result.address == '')){
                fetch(`https://restapi.amap.com/v3/geocode/regeo${this.formatUrl({
                    key: 'f5baa22669fab7fcf7c1a2fbbbed3f25',
                    location: `${result.position[0]},${result.position[1]}`,
                    radius: 1000,
                    poitype: '',
                    extensions: 'all',
                    batch: 'false',
                    roadlevel: '0'
                })}`, {method: 'GET'}).
                then(res => res.json())
                .catch(err => {})
                .then(data => {
                    if(data.status == '1'){
                        let {formatted_address: address} = data.regeocode;
                        locationInfo.address = address || '';

                        this.setLocationInfo(locationInfo);
                        result.status != -1 && func && setTimeout(() => {//获取位置成功，执行提交表单的回调
                            func({...locationInfo, locationEditFields : this.editFieldIds});
                        }, 1000);

                        if(result.status == -1 && func) {
                            Bubble.warning(getLabel(503965,'尚未获取到位置，无法提交流程'), 3);
                            const {controllBottomBtnDisable} = base.allStores.wfOperateStore;
                            controllBottomBtnDisable(false);
                        }
                    }else{
                    }
                });
            } else {
                this.setLocationInfo(locationInfo);
                result.status != -1 && func && setTimeout(() => {//获取位置成功，执行提交表单的回调
                    func({...locationInfo, locationEditFields : this.editFieldIds});
                }, 1000);

                if(result.status == -1 && func) {
                    Bubble.warning(getLabel(503965,'尚未获取到位置，无法提交流程'), 3);
                    const {controllBottomBtnDisable} = base.allStores.wfOperateStore;
                    controllBottomBtnDisable(false);
                }
            }
        });
    }

    formatUrl = params => {
        params = Object.values(params).reduce((a,b,i) => `${a}${Object.keys(params)[i]}=${b}&`, '?');
        return params.substring(0, params.length - 1);
    }

    @action('提交前重新定位')
    locatedBeforeSubmit = (func) => {
        this.setLocationInfo({loaded : false});
        this.getLocaiton(func);
    }

    setLocationInfo = (obj) => {
        this.locationInfo = { ...this.locationInfo, ...obj };
    }

    setFieldObj = (obj) => {
        this.fieldObj = obj;
    }

    addEditFieldIds = (fieldId) => {
        if(this.editFieldIds.indexOf(fieldId) == -1) {
            this.editFieldIds.push(fieldId);
        }
    }

    deleteEditFieldIds = (fieldId) => {
        const index = this.editFieldIds.indexOf(fieldId);
        if(index != -1) {
            this.editFieldIds.splice(index, 1);
        }
    }
}